<?php
namespace Home\Controller;
use Home\Controller\BaseController;
// +----------------------------------------------------------------------
// | Date:2016年12月14日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
class IndexController extends BaseController{
    
    
    /**
     * 首页
     * 
     * date:2016年12月20日
     * author: EK_熊
     */
    public function index(){
        $proModel = D('Product');
        
        //精选案例
        $recommend = $proModel->getListGroup(['recommend_type'=>1],'listorder desc,published desc');
        $this->assign('recommend',$recommend);
        
        //经典案例
        $recommend = $proModel->getListGroup(['recommend_type'=>2],'listorder desc,published desc');
        $this->assign('classics',$recommend);
        
//         //最新作品
//         $newest = $proModel->getListGroup([],'published desc');
//         $this->assign('newest',$newest);
        
//         //用户热门搜索,实际上是按照文章点击数排序
//         $hot = $proModel->getListGroup([],'hits desc');
//         $this->assign('hot',$hot);
        
//         //随机展示
//         $random = $proModel->getListGroup([],'rand()');
//         $this->assign('random',$random);
        
        //自定义推荐 
//         $cateId = D('Admin/Config')->getConfig('pro_index');
//         $custom_map['t_hy|t_lx|t_xq|t_gj|t_jx'] = $cateId['custom_cate_id'];
//         $custom = $proModel->getListGroup($custom_map,'id desc');
//         $this->assign('custom',$custom);
 
        //消费者洞察
        $xfzdc = $proModel->getListGroup(['recommend_type'=>3],'published desc');
        $this->assign('xfzdc',$xfzdc);
        
        
        
        //轮播图
        $slide = M('slide')->where(['status'=>1])->field('slide_url,slide_pic,slide_name,slide_video,type')->order('listorder desc')->select();
        
        
        $this->assign('search_keyword_hot',D('SearchLog')->keyword_hot());
        $this->assign('slide_index',$slide);
        $this->assign('custom_name',$cateId['custom_cate_name']);
        $this->assign('showBg',true);
        R('Public/category');//调用分类数据筛选栏
        $this->display();
    }
    
    /**
     * api 接口，
     * ajax输出奖项名称
     * 
     * date:2017年2月4日
     * author: EK_熊
     */
    public function api_get_prize(){
        $prizeid = I('prizeid');
        $data['list'] = M('Category')->where(['cid'=>['in',$prizeid]])->getField('name',true);
        if(!$data) $this->error('数据获取失败！');
        $data['status'] = 1;
        $this->ajaxReturn($data);
    }
    
    /**
     * 详情页
     * 
     * date:2016年12月29日
     * author: EK_熊
     */
    public function detail(){
        $postId = I('id');
        
        if (isMobile()){
            $this->redirect('detail_mobile',['id'=>$postId]);
            exit();
        }
        $cateIdBox =[];//需要查询的分类id集合
        $searchLog = I('search',[]);
        $proModel = D('Product');
        
        $detail = $proModel->where(['id'=>$postId])->find();
        if (!$detail) $this->_empty();
        
        /* 获取，解析分类筛选查询条件*/
        if (!empty($searchLog)) {
            parse_str(urldecode(I('search')),$searchLog);//函数把查询字符串解析到变量中
            $cateIdBox = array_merge($cateIdBox,$searchLog);
        }
        
        
        /* 把需要查询获取标签名称的id汇集在一起查询 */
        array_push($cateIdBox,$detail['t_gj'],$detail['t_sj']);
        $map_cate['cid'] = ['in',$cateIdBox];
        $cateData = M('Category')->where($map_cate)->getField('cid,name',true);
        
        /* 获取图片路径,如果有视频，要移除第一个元素，因为那是封面 */
        $imageID = explode(',',$detail['image_id']);
        if (!empty($detail['media_id'])) $imageID = array_splice($imageID,1); 
        if ($imageID) {
            $detail['images'] = M('images')->where(['id'=>['in',$imageID]])->field('id,savepath')->select();
        }
        $detail['t_hy'] = $this->_getCatePath($detail['t_hy']);
        $detail['t_xq'] = $this->_getCatePath($detail['t_xq']);
        $detail['t_sj'] = $cateData[$detail['t_sj']];
        $detail['t_gj'] = $cateData[$detail['t_gj']];
        /*文章发布显示日期处理*/
        $publish = '';
        if ($detail['t_sj']) $publish = $detail['t_sj'];
        if ($detail['t_sj_month']) $publish .= $detail['t_sj_month'].'月';
        if ($detail['t_sj_day']) $publish .= $detail['t_sj_day'].'日';
        $detail['t_sj'] = $publish;
        
        /* 处理顶部搜索路径标签，如果没有查询条件，就显示作品的品牌名称 */
        foreach ($searchLog as $k=>$v){
            $searchLogName[] = $cateData[$v];
        }
        $top_label = $searchLog ? $searchLogName : [$detail['brand']];
        
        /* 获取，解析查询条件搜索输入框关键词查询 处理*/
        foreach ($this->searchBar as $k=>$v){
            $search_val = I($k);
            if (!empty($search_val)) {
                $top_label[] = $v.":".$search_val;
            }
        }

        
        $user_like = M('ProductLike')->where(['pro_id'=>$detail['id'],'uid'=>$this->uid])->find();
        $user['like'] = !empty($user_like) ? true : false;//用户数据：点赞数
        $user_label = D('Favorite')->label_in_article($detail['id']);
        $user['isFavorite'] = !empty($user_label) ? true : false; //用户数据：收藏标签
        $user['label'] = !empty($user_label) ? implode(',',$user_label) : ''; //用户数据：收藏标签
        $user_score = M('ProductScore')->where(['pro_id'=>$detail['id'],'uid'=>$this->uid])->getField('score');
        $user['score'] = !empty($user_score) ? $user_score : 0;      //用户数据：作品点评数  
        /*系列作品*/
        if($detail['group_id']){
            $list['group'] = $proModel->getList(['group_id'=>$detail['group_id'],'id'=>['neq',$detail['id']]]);
        }
        /*代理相关作品*/
        if ($detail['brand']){
            $list['brand'] = $proModel->getList(['brand'=>['like',"%{$detail['brand']}%"],'id'=>['neq',$detail['id']]],'published desc',5);
        }
        /*品牌相关作品*/
        if ($detail['agency']){
            $list['agency'] = $proModel->getList(['agency'=>['like',"%{$detail['agency']}%"],'id'=>['neq',$detail['id']]],'published desc',5);
        }

        /*获取评论*/
        $comment = D('Comment')->allComment(1,5,['pro_id'=>$detail['id']]);
        
        /* 文章标签（关键词）处理，转换#分隔符，方便点击触发 */
        if ($detail['keywords']) $keywords = explode(',',$detail['keywords']);
        
        /* 添加浏览记录 */
        if ($this->uid) {
            D('ProductHistory')->history_set($postId,$this->uid);
        }
        /*更新作品浏览点击数*/
        $proModel->where(['id'=>$postId])->setInc('hits');
        
        $this->assign('user',$user);
        $this->assign('userInfo',$this->userInfo);
        $this->assign('comment',$comment);
        $this->assign('list',$list);
        $this->assign('top_label',$top_label);
        $this->assign('keywords',$keywords);
        $this->assign('detail',$detail);
        $this->display();
    }
    
    
    public function detail_mobile(){
        $postId = I('id');
        if (!isMobile()){
            $this->redirect('detail',['id'=>$postId]);
            exit();
        }
        
        $proModel = D('Product');
        
        $detail = $proModel->where(['id'=>$postId])->find();
        $map_cate['cid'] = ['in',[$detail['t_gj'],$detail['t_sj']]];
        $cateData = M('Category')->where($map_cate)->getField('cid,name',true);
        $detail['t_hy'] = $this->_getCatePath($detail['t_hy']);
        $detail['t_xq'] = $this->_getCatePath($detail['t_xq']);
        $detail['t_sj'] = $cateData[$detail['t_sj']];
        $detail['t_gj'] = $cateData[$detail['t_gj']];
        
        /*文章发布显示日期处理*/
        $publish = '';
        if ($detail['t_sj']) $publish = $detail['t_sj'];
        if ($detail['t_sj_month']) $publish .= $detail['t_sj_month'].'月';
        if ($detail['t_sj_day']) $publish .= $detail['t_sj_day'].'日';
        $detail['t_sj'] = $publish;
        
        /* 获取图片路径,如果有视频，要移除第一个元素，因为那是封面 */
        $imageID = explode(',',$detail['image_id']);
//         if (!empty($detail['media_id'])) $imageID = array_splice($imageID,1);
//         if ($imageID) {
//             $detail['images'] = M('images')->where(['id'=>['in',$imageID]])->field('id,savepath')->select();
//         }
            $detail['images'] = M('images')->where(['id'=>['in',$imageID]])->field('id,savepath')->select();
        /*系列作品*/
        if($detail['group_id']){
            $list['group'] = $proModel->getList(['group_id'=>$detail['group_id'],'id'=>['neq',$detail['id']]],'',2);
        }
        /* 文章标签（关键词）处理，转换#分隔符，方便点击触发 */
        if ($detail['keywords']) $keywords = explode(',',str_replace('，',',',$detail['keywords']));
        $this->assign('keywords',$keywords);
        $this->assign('list',$list);
        $this->assign('detail',$detail);
        $this->display();
    }
    
    /**
     * ajax输出，根据组合groupid获取系列作品图片
     * 
     * date:2017年1月17日
     * author: EK_熊
     */
    public function groupImg(){
        $gid = I('groupid');
        $imgid = I('imageid');
        $checkGid = M('ProductGroup')->where(['grp_id'=>$gid])->find();
        if (!$checkGid) $this->error('系列id无效,没有该系列作品');
        
        $imgAryDB = M('Product')->where(['group_id'=>$gid])->getField('image_id',true);
        if (!$imgAryDB) $this->error('没有该系列作品');
        $imgIdStr = implode(',',$imgAryDB);
        $imgData = M('images')->where(['id'=>['in',$imgIdStr]])->field('savepath as src,id')->select();
        
        
        $imgIndex = 0;
        foreach ($imgData as $k=>$v){
            if ($v['id'] == $imgid){
                $imgIndex = $k;
                break;
            }
        }
        $data['data']=$imgData;
        $data['start']=$imgIndex;
        $this->ajaxReturn($data);
        
    }
    
    
    /**
     * 获取用户的全部标签数据
     * 
     * date:2016年12月30日
     * author: EK_熊
     */
    public function userLabel(){
        $term = I('term');
        $data = M('ProductLabel')->where(['uid'=>$this->uid,'label_name'=>['like',"%$term%"]])->field('label_name as value')->select();
        $this->ajaxReturn($data);
    }
    
    
    /**
     * 获取标签名称，包括整个父系家族成员
     * @param number $cid
     * @param array $catePath
     * date:2016年12月29日
     * author: EK_熊
     */
    private function _getCatePath($cid=126,$catePath=[]){
        $cateModel = M('Category');
        $field = 'cid,name,pid';
        $curNode = $cateModel->where(['cid'=>$cid])->field($field)->find();
        if ($curNode['pid'] == '0') return $catePath;
        if ($curNode){
            array_unshift($catePath,['cid'=>$curNode['cid'],'name'=>trim($curNode['name'])]);
            $parentNode = $cateModel->where(['cid'=>$curNode['pid']])->field($field)->find();
            
            if ($parentNode['pid'] == '0') return $catePath;
            array_unshift($catePath,['cid'=>$parentNode['cid'],'name'=>trim($parentNode['name'])]);
            $catePath = $this->_getCatePath($parentNode['pid'],$catePath);
        }
        return $catePath;
    }
    
    
    
    /**
     * 点赞
     * @param unknown $proid
     * date:2016年12月29日
     * author: EK_熊
     */
    public function dolike($proid){
        $proModel = M('Product');
        $likeModel = M('ProductLike');

        $isExist = $likeModel->where(['pro_id'=>$proid,'uid'=>$this->uid])->find();
        
        if ($isExist) $this->error('您已经点赞了！');
        do{
            $proModel->startTrans();
            $errMsg = '';
            $ret = $likeModel->add([
                'uid'=>$this->uid,
                'pro_id'=>$proid,
                'created_time'=>CURRENT_TIME
            ]);
            
            if (!$ret){
                $errMsg = '个人数据添加失败';
                break;
            }
            
            $ret = $proModel->where(['id'=>$proid])->setInc('likes');
            if (!$ret){
                $errMsg = '作品点赞数更新失败';
                break;
            }
            
        }while(false);
        if (!empty($errMsg)){
            $proModel->rollback();
            $this->error('网络异常，操作失败！');
            exit();
        }
        $proModel->commit();
        $this->success('操作完成');
    }
    
    
    
    /**
     * 添加收藏
     * 
     * date:2016年12月30日
     * author: EK_熊
     */
    public function doFavorite(){
        $labelName = I('label');
        $proID = I('proid');
        $oldLbael = I('oldlabel');
        $favModel = D('Favorite');
        if (empty($oldLbael)) {
            $favModel->fav_add($labelName,$proID);
        }else{
            $favModel->fav_edit($labelName,$oldLbael,$proID);
        }
        $errorInfo = $favModel->getError();
        if (!empty($errorInfo)){
            $this->error($errorInfo);
        }
        
        $this->success('操作完成！');
    }
    
    /**
     * 提交评论
     * 
     * date:2016年12月30日
     * author: EK_熊
     */
    public function doComment(){
        $proid = I('proid');
        $parentid = I('parentid',0);
        $content = I('content');
        $to_uid = I('to_uid',0);
        
        if (empty($content)) $this->error('内容不允许为空！'); 
        
        $commentModel = M('Comment');
        $proModel = M('Product');
        $add =[
            'pro_id'=>$proid,
            'url'=>U('index/detail',['id'=>$proid]),
            'uid'=>$this->uid,
            'to_uid'=>$to_uid,
            'email'=>$this->userInfo['eamil'],
            'created_time'=>CURRENT_TIME,
            'content'=>$content,
            'parentid'=>$parentid,
        ]; 
        $ret_comment =$commentModel->add($add); 
        if (!$ret_comment) $this->error('网络异常,提交失败！！');
        $proModel->where(['id'=>$proid])->setInc('comment');
        $data['comment_id'] = $ret_comment;
        $data['created_time'] = CURRENT_TIME;
        $data['to_uid'] = $this->uid;
        $data['status'] = 1;
        $this->ajaxReturn($data);
        
    }
    
    /**
     * 评论加载更多
     * 
     * date:2017年1月12日
     * author: EK_熊
     */
    public function moreComment(){
        $limit = I('limit',5);
        $page = I('page');
        
        $data = D('Comment')->allComment($page,$limit);
        if (!$data) $this->error('数据获取错误');
        $this->ajaxReturn(['status'=>1,'list'=>$data]);
        
    }
    
    /**
     * 提交评分
     * 
     * date:2017年1月3日
     * author: EK_熊
     */
    public function doScore(){
        $proid = I('proid');
        $score = I('score');
        $scoreModel = M('ProductScore');
        
        if ($score == 0) $this->error('分数 不允许为0');
        $isExist = $scoreModel->where(['uid'=>$this->uid,'pro_id'=>$proid])->find();
        
        if ($isExist) $this->error('您已经提交了评分，不可重复提交！');
        $addScore = $scoreModel->add([
            'uid'=>$this->uid,
            'created_time'=>CURRENT_TIME,
            'pro_id'=>$proid,
            'score'=>$score,
        ]);
        if (!$addScore) $this->error('评分添加失败！'); 
        $scoreAvg = $scoreModel->field('avg(score) as score')->find();
        $updatePro = M('Product')->where(['id'=>$proid])->setField('score',$scoreAvg['score']); 
        if (!$updatePro) $this->error('评分更新失败！');
        $this->success('操作完成！');
        
        
    }
    
    public function test($id){
        $user = M('Product');
        $a = $user->where(["id"=>$id])->select();
        dump($user->_sql());
        dump($a);
    }

}